import * as echarts from 'echarts'
import { useEffect, useRef } from 'react'
/*
柱状图
const data = [{ year: '1991', value: 3, type: 'London' }]
const xAxisLabel = {'1991': '1991'}
const yAxisLabel = {3: '3'}
<BarChart data={data} xField="year" yField="value" seriesField="type" xAxisLabel={xAxisLabel} yAxisLabel={yAxisLabel} height={300}/>
*/
const BarChart = ({ data, xField, yField, seriesField, xAxisLabel, yAxisLabel, height = 400 }) => {
  const chartRef = useRef(null)
  useEffect(() => {
    // 初始化图表实例
    const chartInstance = echarts.init(chartRef.current)
    // 配置图表
    const option = {
      tooltip: {
        trigger: 'axis', // 设置触发类型为基于坐标的提示框
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      xAxis: {
        data: data.map(item => item[xField]),
        axisLabel: {
          formatter: val => xAxisLabel[val] || val
        }
      },
      yAxis: {
        axisLabel: {
          formatter: val => yAxisLabel[val] || val
        }
      },
      series: data.reduce((acc, item) => {
        if (!acc.some(accItem => accItem.name === item[seriesField])) {
          acc.push({
            name: item[seriesField],
            type: 'bar',
            data: data.filter(d => d[seriesField] === item[seriesField]).map(d => d[yField])
          })
        }
        return acc
      }, [])
    }
    // 渲染图表
    chartInstance.setOption(option)
    // 监听窗口大小变化事件，以重新调整图表尺寸
    window.addEventListener('resize', () => chartInstance.resize())
    // 清理函数
    return () => {
      chartInstance.dispose()
      window.removeEventListener('resize', () => chartInstance.resize())
    }
  }, [data, xField, yField, seriesField, xAxisLabel, yAxisLabel])
  return <div ref={chartRef} style={{ height }} />
}
export default BarChart
